package org.BUPT.domain.service.impl;

import org.BUPT.domain.service.AnswerService;
import org.BUPT.infrastructure.persistent.DAO.AnswerDAO;
import org.BUPT.infrastructure.persistent.DAO.CommentDAO;
import org.BUPT.infrastructure.persistent.DAO.LikeDAO;
import org.BUPT.infrastructure.persistent.po.Answer;
import org.BUPT.infrastructure.persistent.po.Comment;
import org.BUPT.infrastructure.persistent.po.Like;
import org.BUPT.infrastructure.persistent.po.LikePrimaryKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class AnswerServiceImpl implements AnswerService {
    @Autowired
    AnswerDAO answerDAO;
    @Autowired
    CommentDAO commentDAO;
    @Autowired
    LikeDAO likeDAO;

    public Answer saveAnswer(Answer answer){
        return answerDAO.save(answer);
    }

    public Answer getAnswer(int answerId){
        return answerDAO.findAnswerByIdAndIsDel(answerId,0);
    }
    public boolean isAnswerLiked(int userId,int answerId){
        return likeDAO.getLikeOfAnswerByUser(userId,answerId)!=null;
    }
    public boolean isAnswered(int questionId,int userId){
        return answerDAO.findAnswerByQuestionIdAndUserIdAndIsDel(questionId,userId,0)!=null;
    }

    public Set<Integer> getLikedUserId(int answerId){
        return new HashSet<Integer>(likeDAO.getLikeCountOfAnswer(answerId));
    }
    public void likeAnswer(int userId,int answerId){
        likeDAO.save(
                new Like()
                        .setLikePrimaryKey(
                                new LikePrimaryKey()
                                        .setUserId(userId)
                                        .setAnswerId(answerId)
                        ).setCreateTime(new Date())
        );
    }
    public void dislikeAnswer(int userId,int answerId){
        likeDAO.delete(
                new Like()
                        .setLikePrimaryKey(
                                new LikePrimaryKey()
                                        .setUserId(userId)
                                        .setAnswerId(answerId)
                        )
        );
    }
    public List<Comment> getCommentsOfAnswer(int answerId){
        return commentDAO.findAllByAnswerIdAndParentIdEqualsAndIsDel(answerId,-1,0);
    }
}
